package com.zenika.zenbinding.client.converter;

import java.util.Date;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.zenika.zenbinding.client.exception.ConverterException;
import com.zenika.zenbinding.client.exception.DataMessage;

/**
 * Converter for the Date class.
 * 
 * @author Zenika
 */
public class DateConverter implements Converter {

	private static final DateTimeFormat dateFormat = DateTimeFormat.getFormat("dd/MM/yyyy");

	public String fromObjectToString(Object object) throws ConverterException {

		if (object == null)
			return null;

		Date date = (Date) object;
		return dateFormat.format(date);
	}

	public Object fromStringToObject(String string) throws ConverterException {
		if (string == null || string.length() == 0)
			return null;

		if (!this.validationDate(string)) {
			this.error();
		}
		int jour = Integer.parseInt(string.substring(0, 2));
		int mois = Integer.parseInt(string.substring(3, 5)) - 1;
		int annee = Integer.parseInt(string.substring(6, 10)) - 1900;
		return new Date(annee, mois, jour, 0, 0, 0);
	}

	public void error() throws ConverterException {
		throw new ConverterException(new DataMessage("Please enter a valid date: dd/mm/yyyy"));
	}

	private boolean validationDate(String maDate) {
		if (maDate.length() != 10) {
			return false;
		}
		char barre = '/';
		if (maDate.charAt(2) != barre | maDate.charAt(5) != barre) {
			return false;
		}

		int jour = 0;
		int mois = 0;
		int annee = 0;
		try {
			jour = Integer.parseInt(maDate.substring(0, 1));
			mois = Integer.parseInt(maDate.substring(3, 4));
			annee = Integer.parseInt(maDate.substring(6, 9));
		} catch (Exception e) {
			return false;
		}

		if (mois < 13) {
			if (mois == 2) {
				if (annee % 4 == 0 | jour > 29) {
					return false;
				} else if (jour > 28) {
					return false;
				}
			} else if (mois == 4 | mois == 6 | mois == 9 | mois == 11) {
				if (jour > 30) {
					return false;
				}
			} else if (jour > 31) {
				return false;
			}
		} else {
			return false;
		}
		return true;
	}

}
